package com.xunfei.noteapp.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.xunfei.noteapp.R
import com.xunfei.noteapp.data.Note
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale


class NoteAdapter(
    private val itemList: MutableList<Note>,
    private val onItemLongClick: (Note,Int) -> Boolean,
    private val onItemClick: (Note) -> Unit = {}
): RecyclerView.Adapter<NoteAdapter.NoteViewHolder>(){
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): NoteViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.notelist,parent,false)
        return NoteViewHolder(view)
    }

    override fun onBindViewHolder(
        holder: NoteViewHolder,
        position: Int
    ) {
        holder.bind(itemList[position],position)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    fun addData(note:Note){
        itemList.add(note)
        notifyDataSetChanged()
    }

    fun deleteData(note:Note){
        itemList.remove(note)
        notifyDataSetChanged()
    }

    fun deleteDataById(position:Int){
        if (position in 0 until itemList.size) {
            itemList.removeAt(position)
            notifyItemRemoved(position)
        }
    }

    fun updateAllData(newList: MutableList<Note>){
        itemList.clear()
        itemList.addAll(newList)
        notifyDataSetChanged()
    }

    inner class NoteViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
        private var title: TextView = itemView.findViewById(R.id.tvtitle)
        private var timestamp: TextView = itemView.findViewById(R.id.tvtimestamp)
        private var content: TextView = itemView.findViewById(R.id.tvcontent)

        fun bind(note: Note,position: Int){
            title.text = note.title
            timestamp.text = timestampToDateTime(note.timestamp)
            content.text = note.content

            itemView.setOnClickListener {
                onItemClick(note)
            }

            itemView.setOnLongClickListener {
                onItemLongClick(note,position)
            }
        }

        fun timestampToDateTime(timestamp: Long, pattern: String = "yyyy-MM-dd HH:mm:ss", locale: Locale = Locale.getDefault()): String {
            val date = Date(timestamp)
            val format = SimpleDateFormat(pattern, locale)
            return format.format(date)
        }


    }
}